//
//  PDImageSelectUtil.swift
//  ZYA
//
//  Created by 邱仙凯 on 2021/7/15.
//  Copyright © 2021 aowang. All rights reserved.
//

import UIKit

import SKPhotoBrowser

import Kingfisher



protocol PDImageUtilDelegate: AnyObject {
    func dealBeforeAddImages(_ util:PDImageSelectUtil, imgs:[UIImage]) -> [UIImage]  // 添加到图片列表前处理图片，比如加水印等
    func addImages(_ util:PDImageSelectUtil, imgs:[UIImage])  // 把添加了的图片告诉使用者
    func addFiles(_ util:PDImageSelectUtil, files:[FileAssistModel])  // 把添加了的文件告诉使用者
    func deleteImage(_ util:PDImageSelectUtil, index:Int)  //  删除告诉使用者
    func inputRealText(_ util:PDImageSelectUtil,str:String, index:Int)  //  输入了实际数量

    func checkAction(_ util:PDImageSelectUtil, index:Int)  //  识别按钮点击

}
extension PDImageUtilDelegate {
    func dealBeforeAddImages(_ util:PDImageSelectUtil, imgs:[UIImage]) -> [UIImage]  {  // 扩展为了默认，非必须继承
        return imgs
    }
    func addFiles(_ util:PDImageSelectUtil, files:[FileAssistModel])  {  // 扩展为了默认，非必须继承
        
    }
}
let exHeight4Cell:CGFloat = 70
class PDImageSelectUtil: FormItem,UICollectionViewDelegate,UICollectionViewDataSource,UITextFieldDelegate {
    
    weak var ksDelegate: PDImageUtilDelegate?
    var collectionView:UICollectionView!
    // 图片    识别数量   实际数量
    lazy var dataArray =  [(UIImage,String?,String?)]()
    lazy var fileArray = [FileAssistModel]()
    fileprivate let layout = UICollectionViewFlowLayout()
    var viewOnly = false {
        didSet {
            self.collectionView.reloadData()
        }
    }
    var maxImgCount = 8 {
        didSet {
            self.collectionView.reloadData()
        }
    }
    var numberOfRow:CGFloat = 4 {
        didSet {
            layout.itemSize = CGSize(width: self.ks_width/numberOfRow - numberOfRow, height: self.ks_width/numberOfRow - numberOfRow + exHeight4Cell)
            self.collectionView.reloadData()
        }
    }
    var picType:[PictureType] = [.takePicture,.albumPicture]
    var scrollDirection:UICollectionView.ScrollDirection = .vertical
    // 外面传进来的图片文件资源域名头
    var httpHeader = ""
 
    init(frame: CGRect,httpHeader:String,maxImgCount:Int = 8,numberOfRow:CGFloat = 4,picType:[PictureType] = [.takePicture,.albumPicture],scrollDirection:UICollectionView.ScrollDirection = .vertical,viewOnly:Bool = false) {
        super.init(frame: frame)
        self.collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        self.addSubview(self.collectionView)
         self.viewOnly = viewOnly
        self.maxImgCount = maxImgCount
        self.numberOfRow = numberOfRow
        self.picType = picType
        self.httpHeader = httpHeader
        self.scrollDirection = scrollDirection
        self.initView()
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        self.initView()
    }
    func initView () {
        self.backgroundColor = Theme.pureWhite()
        self.collectionView?.backgroundColor = Theme.pureWhite()
        layout.itemSize = CGSize(width: self.ks_width/numberOfRow - numberOfRow, height: self.ks_width/numberOfRow - numberOfRow + exHeight4Cell)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = self.scrollDirection
        self.collectionView.collectionViewLayout = layout
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(PDImageUtilCell.self, forCellWithReuseIdentifier: PDImageUtilCell.identifier)
        
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let sumCount = self.dataArray.count + self.fileArray.count
        if sumCount == maxImgCount {
            return sumCount
        } else {
            return sumCount + 1
        }
        
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell  = collectionView.dequeueReusableCell(withReuseIdentifier: PDImageUtilCell.identifier, for: indexPath as IndexPath) as! PDImageUtilCell
        
        let sumCount = self.dataArray.count + self.fileArray.count
        if (indexPath.row == sumCount) { // 最后一个为添加按钮
            if viewOnly {
                cell.imgBtn.isHidden = true
                cell.deleteBtn.isHidden = true
            } else {
                cell.imgBtn.isHidden = false
                cell.imgBtn.setBackgroundImage(UIImage(named:"ksphoto_add"), for: .normal)
                cell.imgBtn.setTitle("", for: .normal)
                cell.deleteBtn.isHidden = true
            }
            
            cell.showInputFunc(false)
        } else {
            if indexPath.row < self.dataArray.count {
                cell.imgBtn.setBackgroundImage(dataArray[indexPath.row].0, for: .normal)
                cell.imgBtn.setTitle("", for: .normal)
            } else {
                 cell.imgBtn.setBackgroundImage(nil, for: .normal)
                cell.imgBtn.setTitle(self.fileArray[indexPath.row - self.dataArray.count].fName.unwrap, for: .normal)
            }
            
            cell.imgBtn.isHidden = false
            if viewOnly {
                cell.deleteBtn.isHidden = true
            } else {
                cell.deleteBtn.isHidden = false
            }
            let ttt = !dataArray[indexPath.row].1.unwrap.isEmpty ? ("识别数:" + dataArray[indexPath.row].1!) : "点击识别"
            cell.checkBtn.setTitle(ttt, for: .normal)
            
            cell.realText.text = dataArray[indexPath.row].2.unwrap
            cell.realText.tag = indexPath.row
            cell.realText.delegate = self
            
            cell.showInputFunc(true)
            
 
        }
        
        
        cell.imgBtn.tag = indexPath.row
        cell.imgBtn.addTarget(self, action:#selector(imgAction(sender:)) , for:.touchUpInside )
        cell.deleteBtn.tag = indexPath.row
        cell.deleteBtn.addTarget(self, action: #selector(deleteImg(sender:)), for: .touchUpInside)
        cell.checkBtn.tag = indexPath.row
         cell.checkBtn.addTarget(self, action: #selector(checkAction(sender:)), for: .touchUpInside)
 
        return cell
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if let delegate = self.ksDelegate {
            delegate.inputRealText(self, str: textField.text.unwrap, index: textField.tag)
        }
    }
    
    @objc func imgAction (sender:UIButton) {
       
        let sumCount = self.dataArray.count + self.fileArray.count
        
        if (sender.tag == sumCount) {
            if dataArray.count == maxImgCount {
                KSToast("只能选\(maxImgCount)张")
                return
            }
           
            let alertSheet =  KSImagePicker.shared.config(picType: picType,cameraAction: { img in
                
         
                let imgsTreated = self.pretreatmentBeforeAddImgs([img])
                let rrr = imgsTreated.compactMap { ($0,"","") }
        
                self.dataArray += rrr
        
                if let delegate = self.ksDelegate {
                    delegate.addImages(self,imgs: imgsTreated)
                }
                self.collectionView.reloadData()
             
            },photpMaxImagesCount:self.maxImgCount - self.dataArray.count,photoAction: { imgs,assets in
                
                        var newPho = [UIImage]()
                let imgsTreated = self.pretreatmentBeforeAddImgs(imgs)
                        newPho += imgsTreated
                
                let rrr = imgsTreated.compactMap { ($0,"","") }
                self.dataArray += rrr
                
                if let delegate = self.ksDelegate {
                            delegate.addImages(self,imgs: newPho)
                        }
                        self.collectionView.reloadData()
               
            }) {
                
                let fileVC = UIDocumentPickerViewController(documentTypes: ["public.image", "public.audio", "public.movie", "public.text", "public.item", "public.content", "public.source-code"], in: .import)
                fileVC.delegate = self
                fileVC.modalPresentationStyle = .formSheet
                if let topVC = getTopVC() {
                    topVC.present_FullScreen(to: fileVC)
                }
                
            }
            // 3 跳转
            if let topVC = getTopVC() {
                topVC.present(alertSheet, animated: true, completion: nil)
            }
        }else {
            // MARK: - 预览
            if sender.tag < self.dataArray.count {
                var photos = [SKPhoto]()
                // add some UIImage
                self.dataArray.forEach {
                    let image = SKPhoto.photoWithImage($0.0)
                    photos.append(image)
                    
                }
                // 2. create PhotoBrowser Instance, and present from your viewController.
                let browser = SKPhotoBrowser(photos: photos)
                browser.initializePageIndex(sender.tag)
                if let topVC = getTopVC() {
                    topVC.present(browser, animated: true, completion: nil)
                }
                
            } else {
                if let urlX = self.fileArray[sender.tag - self.dataArray.count].fUrl {
                    let cwebV = CommonWebController()
                    cwebV.reportUrl = "\(self.httpHeader)\(urlX)"
                    cwebV.title = self.fileArray[sender.tag - self.dataArray.count].fName.unwrap
                    if let topVC = getTopVC() {
                        topVC.navigationController?.pushViewController(cwebV, animated: true)
                    }
                    
                   
                } else {
                    if UIApplication.shared.canOpenURL(URL(string: "shareddocuments://")!) {
                        UIApplication.shared.open(URL(string: "shareddocuments://")!, options: [:], completionHandler: nil)
                    } else {
                        KSToast("请到文件app查看")
                    }
                }
                
            }
   
        }
    }
    // 识别猪只事件
        @objc private  func checkAction(sender:UIButton) {
            if let delegate = ksDelegate {
                delegate.checkAction(self,index: sender.tag)
            }
        }
// 删除项目，包括图片和文件
    @objc private  func deleteImg(sender:UIButton) {
        if let delegate = ksDelegate {
            delegate.deleteImage(self,index: sender.tag)
        }
    }
    // 删除本地项目，包括图片和文件
    func deleteLocalImg(tag:Int) {
        if tag < self.dataArray.count {
            self.dataArray.remove(at: tag)
        } else {
            self.fileArray.remove(at: tag -  self.dataArray.count)
        }
        self.collectionView.reloadData()
    }
  
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    // 预处理图片，如：打水印等
    func pretreatmentBeforeAddImgs(_ photos: [UIImage]) -> [UIImage] {
        if let delegate = ksDelegate {
            return  delegate.dealBeforeAddImages(self, imgs: photos)
        } else {
            return photos
        }
        
        
    }
    
    
}
 
extension PDImageSelectUtil {
    // 直接用图片展示图片
    public func showAllPicture(picS:[(UIImage,String,String)]) {
          self.dataArray = picS
        self.collectionView.reloadData()
    }
    // 展示文件
    public func showFiles(files:[FileAssistModel]) {
        self.fileArray = files
        self.collectionView.reloadData()
    }
    /// 用url展示图片 支持 String  和 FileType
    public func showPicture(urls:[(String,String,String)],defaultImg:DefaultImg = .loading,backImgs:@escaping (([UIImage]?)->())) {
        
        
        guard urls.count > 0 else {
            self.dataArray.removeAll()
            self.collectionView.reloadData()
            backImgs(nil)
            return
        }
        // ImageCache，默认是
        let cache = ImageCache.default
        if defaultImg == .loading {
            
            self.dataArray = urls.compactMap { (UIImage.gif(name: "ks_jiazaizhong")!,$0.1,$0.2) }
            
         } else {
            self.dataArray = urls.compactMap { (UIImage.gif(name: "ks_avatarImage")!,$0.1,$0.2) }

         }
        
        
        let tempVO = self.viewOnly
        self.viewOnly = true
        self.collectionView.reloadData()
        DispatchQueue.global().async {
            for i in 0..<urls.count {
                
                // 判定图片是否存在
                let cached = cache.imageCachedType(forKey:urls[i].0)
                var cachedImg:UIImage?
                if  cached == .disk {
                    cache.retrieveImageInDiskCache(forKey: urls[i].0, completionHandler: { (result) in
                        switch result {
                        case .success(let img):
                            cachedImg = img
                            self.dataArray[i].0 = cachedImg!
                        default:
                            break
                        }
                     })
                    
                } else if cached == .memory {
                    cachedImg = cache.retrieveImageInMemoryCache(forKey:urls[i].0)
                    self.dataArray[i].0 = cachedImg!
                    continue
                } else {
                    print(urls[i])
                    if  let nsd = NSData(contentsOf:NSURL(string: urls[i].0)! as URL) {
                        
                        if let img = UIImage(data: nsd as Data) {
                            cache.store(img, forKey: urls[i].0)
                            self.dataArray[i].0 = img
                        } else {
                            let img = UIImage(named:"ks_error.jpg")!
                            self.dataArray[i].0 = img
                        }
                        
                    }
                    
                }
                
            }
            DispatchQueue.main.async {
                // 主线程中
                self.viewOnly = tempVO
                self.collectionView.reloadData()
                let imgArr = self.dataArray.compactMap { $0 as? UIImage }
                backImgs(imgArr)
            }
            
        }
        
    }

    
}

extension PDImageSelectUtil:UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        if let first = urls.first  {
            first.startAccessingSecurityScopedResource()
            let fileCoordinator = NSFileCoordinator()
            let error = NSError()
            
            fileCoordinator.coordinate(readingItemAt: first, options: [], error: nil) { (newUrl) in
                
                let fileName = newUrl.lastPathComponent
                
                do {
                    if self.picType.contains(.pdfFile) && !self.picType.contains(.allfile) {
                        guard fileName.contains(".pdf") || fileName.contains(".PDF") else {
                            KSToast("该功能仅支持pdf格式")
                            return
                        }
                    }
                    
                    let fileData = try NSData(contentsOf: newUrl, options: .dataReadingMapped)
                    let model = FileAssistModel(json:"")
                    model.fName = fileName
                    model.fData = fileData as Data
                    self.fileArray.append(model)
                    self.collectionView.reloadData()
                    if let delegate = ksDelegate {
                            delegate.addFiles(self, files: [model])
                        }
                    
                    first.stopAccessingSecurityScopedResource()
                    
                } catch {
                    print("error")
                    
                }
                
            }
            
        }
        
        
        print(urls)
    }
    
    
}
